#include "../../macro.h"
#include <iostream>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <sys/socket.h>
#include <string.h>
#include <unistd.h>

using std::cout;
using std::endl;

void server(char **argv)
{
    int sfd = socket(AF_INET, SOCK_STREAM, 0);
    ERR_CHECK(sfd, -1, "socket")

    sockaddr_in ser_addr{};
    // ser_addr.sin_port = htons(atoi(argv[2]));
    ser_addr.sin_port = htons(2000);
    ser_addr.sin_family = AF_INET;
    // ser_addr.sin_addr.s_addr = inet_addr(argv[1]);
    ser_addr.sin_addr.s_addr = inet_addr("127.0.0.1");

    int ret = connect(sfd, (sockaddr *)&ser_addr, sizeof(ser_addr));
    ERR_CHECK(ret, -1, "connect")

    char buf[1024];
    fd_set rdset;
    while(1){
        FD_ZERO(&rdset);
        bzero(buf, 1024);
        FD_SET(STDIN_FILENO, &rdset);
        FD_SET(sfd, &rdset);

        ret = select(sfd + 1, &rdset, nullptr, nullptr, 0);
        ERR_CHECK(ret, -1, "select")

        if(FD_ISSET(STDIN_FILENO, &rdset)){
            ret = read(STDIN_FILENO, buf, sizeof(buf));
            ERR_CHECK(ret, -1, "recv")

            ret = send(sfd, buf, strlen(buf) - 1, 0);
            ERR_CHECK(ret, -1, "send")
        }
        if(FD_ISSET(sfd, &rdset)){
            ret = recv(sfd, buf, sizeof(buf), 0);
            ERR_CHECK(ret, -1, "recv")

            if(ret > 0){
                cout << "recv: " << buf << endl;
            }else{
                break;
            }
        }
    }

    close(sfd);
}

int main(int args, char **argv)
{
    server(argv);
    return 0;
}